package com.itheima.interceptor;
import com.aliyuncs.utils.StringUtils;
import com.itheima.Utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头的token
        String headerToken = request.getHeader("token");
        //2.判断token是否为空
        if (StringUtils.isEmpty(headerToken)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {   //3.解析token，失败401
            JwtUtils.parseJWT(headerToken);
        }catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }//4.放行
        return true;
    }
}
